package com.suns.client;

import com.suns.HelloServiceGrpc;
import com.suns.HelloServiceGrpc.HelloServiceBlockingStub;
import com.suns.SimpleRequest;
import com.suns.SimpleRequest.Builder;
import com.suns.SimpleResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * @author xiangminwen
 * @date 2024/4/3 11:13
 */
public class GrpcClient {

    public static void main(String[] args) throws Exception {
        //创建通信管道
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9000).usePlaintext().build();
        try {
            //获得代理对象Stub
            HelloServiceBlockingStub serviceStub = HelloServiceGrpc.newBlockingStub(channel);
            //组装参数
            Builder request = SimpleRequest.newBuilder();
            request.setName("client").setAge(10);
            request.addCode("code1").addCode("code2");
            //RPC调用获取响应
            System.out.println(serviceStub.hello(request.build()).getData());
            //返回多个
            Iterator<SimpleResponse> responseIte = serviceStub.hello1(request.build());
            while (responseIte.hasNext()) {
                SimpleResponse response = responseIte.next();
                System.out.println(response.getData());
            }

        } finally {
            if (!channel.isShutdown()) {
                channel.shutdown().awaitTermination(6, TimeUnit.SECONDS);
            }
        }
    }
}
